package java0423;

import java.sql.*;
import java.util.Scanner;

// 模糊查询
public class Test {
    public static void main(String[] args) {
        // 数据库连接对象
        Connection conn = null;
        // 数据库操作对象
        PreparedStatement ps = null;
        // 查询结果集对象
        ResultSet rs = null;
        try {
            // 1. 注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2. 创建数据库连接对象
            String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true";
            String username = "root";
            String password = "991025";
            conn = DriverManager.getConnection(url, username, password);
            // 3. 创造数据库操作对象
            String sql = "select * from user where name like ?";
            ps = conn.prepareStatement(sql);
            System.out.println("请输入模糊查关键字:");
            Scanner scanner = new Scanner(System.in);
            String keyWord = scanner.next();
            String name = "%" + keyWord + "%";
            // 替换
            ps.setString(1, name);
            // 4. 执行 sql 语句
            rs = ps.executeQuery();
            // 5. 操作查询结果集
            while (rs.next()) {
                int id = rs.getInt("id");
                String un = rs.getString("name");
                String pw = rs.getString("password");
                System.out.println(id + "," + un + "," + pw);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            // 6. 释放资源
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                if (ps != null) {
                    ps.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
